package com.qipay.api.callback.controller.v1;

import com.qipay.api.callback.controller.v1.vo.FuHuiCallBackData;
import com.qipay.baas.model.Order;
import com.qipay.core.help.BeanHelper;
import com.qipay.order.service.OrderService;
import com.qipay.sp.SpConfigService;
import com.qipay.sp.excutor.fuhuipay.FHSignUtils;
import com.qipay.sp.excutor.fuhuipay.FuHuiWapExcutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/callback/v1/fuhui")
/**
 * 付汇回调
 */
public class FuHuiCallbackController {
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
	OrderService orderService;
    @Autowired
    SpConfigService spConfigService;

    @RequestMapping(value = "/wap" ,method = RequestMethod.POST)
    private String wap(@RequestBody FuHuiCallBackData fuHuiCallBackData,
            HttpServletRequest request,HttpServletResponse response
    ) throws Exception {
        logger.info("request from " + request.getRequestURI() + ", request body:" + fuHuiCallBackData);
        if(fuHuiCallBackData!=null&&"00".equals(fuHuiCallBackData.getCode())){
            String tradeNo = fuHuiCallBackData.getMerchant_req_no();
            Order order = orderService.getByTradeNo(tradeNo);
            if(order==null) {
                logger.info("回调失败：查无此订单="+tradeNo);
                return "fail";
            }

            Map<String, Object> keyValues = spConfigService.getKeyValues(order.getSpId());
            String key = keyValues.get(FuHuiWapExcutor.PAY_KEY).toString();
            Map<String, Object> paramso = new HashMap<>();
            boolean check=FHSignUtils.checkSign(BeanHelper.beanToMap(new HashMap<String,String>(),fuHuiCallBackData),key);
            if(check){
                orderService.setOrderSuccess(order.getId(), null);
                return "success";
            }else {
                logger.info("回调失败：签名sign不一致，tradeNo="+tradeNo);
            }
        }
        return "fail";
    }
}
